package com.smartTerminal.perMatters.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smartTerminal.perMatters.entity.MyAppointment;
import com.smartTerminal.perMatters.entity.StrObject;
import com.smartTerminal.perMatters.service.GetOrItemsService;
import com.smartTerminal.perMatters.service.MyAppointmentService;
import com.smartTerminal.perMatters.service.SiteService;
import com.smartTerminal.user.entity.User;
import com.smartTerminal.utils.Base64Util;
import com.smartTerminal.utils.DateUtils;
import com.smartTerminal.utils.StringUtils;
import com.smartTerminal.utils.XmlUtils;

/**
 * 处理我的预约
 * 
 * @author wantao
 * @Date 2018年1月9日
 * 
 */
@Controller
public class MyAppointmentController {

	@Autowired
	private MyAppointmentService myAppointmentService;
	@Autowired
	private GetOrItemsService getOrItemsService;
	@Autowired
	private SiteService siteService;

	@RequestMapping("getMessage")
	public String getMessage(HttpServletRequest request,String itemid,String deptName,String itemName){
		//为维护系统添加的type和types，后续可以删除
		String types = request.getParameter("types");
		String type = request.getParameter("type");
		if("3".equals(type) || "1".equals(types)){
			request.setAttribute("tips", "系统正在开发中。。。。。。");
			return "user/error";
		}
		User user = (User) request.getSession().getAttribute("USER");
		request.getSession().setAttribute("itemid", itemid);
		request.getSession().setAttribute("deptName", deptName);
		request.getSession().setAttribute("itemName", itemName);
		if (user == null) {
			user = new User();
			user.setService("redirect:/getItemAppointmentTime");
			request.setAttribute("user", user);
			return "/user/login";
		}
		return "redirect:/getItemAppointmentTime";
	}
	/**
	 * 获取可预约时间，获取预约时间时间和事项
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getItemAppointmentTime")
	public String getItemAppointmentTime(HttpServletRequest request,
			HttpServletResponse response) {
		User user = (User) request.getSession().getAttribute("USER");
		String itemid = (String) request.getSession().getAttribute("itemid");
		String deptName = (String) request.getSession().getAttribute("deptName");
		String itemName = (String) request.getSession().getAttribute("itemName");
		String nowTime = null;
		String SITE_ID = siteService.getSiteAndItemList(deptName,3);
		try {
			String dateTime = null;
			
			List<StrObject> strObject = new ArrayList<StrObject>();  //总时间的上午
			//获取当前时间的下一周时间
			for (int i = 0; i < 7; i++) {
				StrObject so = new StrObject();
				List<String> mSl = new ArrayList<String>(); //一天的上午
				List<String> aSl = new ArrayList<String>(); //一天的上午
				//获取当前时间
				nowTime = DateUtils.toHyphenatedYyyyMmdd(DateUtils.getNumToDate(new Date(), i)).toString();
				//获取星期
				String week = DateUtils.getWeekOfDate(new SimpleDateFormat("yyyy-MM-dd").parse(nowTime)); 
				//排除周六周日
				if("星期六".equals(week) || "星期日".equals(week)){
					continue;
				}
				so.setWeek(week);
				so.setDate(nowTime.substring(0, 10));
				dateTime = myAppointmentService.getItemAppointmentTime(itemid,nowTime);
				JSONObject timeObj = JSON.parseObject(dateTime);
				if (timeObj.getString("code").equals("0")) {
					String DATA = timeObj.getString("DATA");
					JSONObject dateTimeObj = JSON.parseObject(DATA);
					String time = dateTimeObj.getString("YYSJ");
					time = time.substring(1, time.length()-1);
					if(time.length()>5){
						String[] str = time.split(",");
						for (int i2 = 0; i2<str.length;i2++) {
							String housStr = str[i2].split(" ")[1];
							//10:00之前
							if(housStr.length()==10){
								mSl.add(housStr.substring(0, housStr.length()-1));
							}
							//9:00-10:00之间
							if(housStr.length()==11){
								mSl.add(housStr.substring(0, housStr.length()-1));
							}
							//10:00之后
							if(housStr.length()==12){
								//10:00之后12:00之前
								if(Integer.parseInt(housStr.substring(0, 2))<=12){
									mSl.add(housStr.substring(0, housStr.length()-1));
								}
								//12:00之后
								if(Integer.parseInt(housStr.substring(0, 2))>12){
									aSl.add(housStr.substring(0, housStr.length()-1));
								}
							}
						}
					}
				}
				so.setmStrList(mSl);
				so.setaStrList(aSl);
				strObject.add(so);
			}
			/*for (int i = 0;i<strObject.size();i++) {
				StrObject S = strObject.get(i);
				for(int i1 =0;i1<S.getStrList().size();i1++){
					System.out.println("第" +i+"个对象，第"+i1+"条"+S.getStrList().get(i1).length());
				}
				
			}*/
			request.setAttribute("strObject", strObject);
			request.setAttribute("user", user);
			request.setAttribute("SITE_ID", SITE_ID);
			request.setAttribute("itemid", itemid);
			request.setAttribute("deptName", deptName);
			request.setAttribute("itemName", itemName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/permatters/order";
	}
	/**
	 * 获取预约信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("saveJsp")
	public String saveJsp(HttpServletRequest request,HttpServletResponse response){
		User user = (User) request.getSession().getAttribute("USER");
		String day = request.getParameter("day");
		String sjd = request.getParameter("sjd");
		String usertime = day+" "+sjd;  //处理时间2018-1-19 00:00
		String useritemId = request.getParameter("itemid");
		String userdeptId = request.getParameter("SITE_ID");
		request.setAttribute("usertime", usertime);
		request.setAttribute("useritemId", useritemId);
		request.setAttribute("userdeptId", userdeptId);
		request.setAttribute("user", user);
		
		request.setAttribute("deptName", request.getSession().getAttribute("deptName"));
		request.setAttribute("itemName", request.getSession().getAttribute("itemName"));
		return "permatters/addOrder";
	}
	
	/**
	 * 保存预约信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("saveAppointmentInfo")
	public String saveAppointmentInfo(HttpServletRequest request,
			HttpServletResponse response) {
		// 保存预约信息
		String ORDER_NO = null;
		String userName = request.getParameter("userName");
		String userPhone = request.getParameter("userPhone");
		String idcard = request.getParameter("idcard");
		String time = request.getParameter("time");
		String itemId = request.getParameter("itemId");
		String siteid = request.getParameter("siteid");
		String base64 = null;
		User user = (User) request.getSession().getAttribute("USER");
		String authToken = user.getAuthToken();
		JSONObject obj = new JSONObject();
		try {
			String error = myAppointmentService.checkError(userName,userPhone,idcard);
			if(error != null){
				request.setAttribute("tips", error);
				return "user/error";
			}
			String xmlInfo = XmlUtils.createXml(userName, userPhone, idcard, time, itemId, siteid);
			ORDER_NO = myAppointmentService.saveAppointmentInfo(authToken,xmlInfo);
			if(ORDER_NO.length()<5){
				if("-1".equals(ORDER_NO)){
					request.setAttribute("tips", "同一身份证号码、同一事项、同一时间段一天只能预约一次!");
					return "user/error";
				}else{
					request.setAttribute("tips", "预约失败，请联系管理员！");
					return "user/error";
				}
			}
			obj.put("type", "1");
			obj.put("data", ORDER_NO);
			base64 = Base64Util.toBase64(obj, 100, 100);
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute("base64", base64);
		request.setAttribute("ORDER_NO", ORDER_NO);
		request.setAttribute("QR_INFO", obj.toJSONString().replaceAll("\"", "'"));
		request.getSession().removeAttribute("itemid");
		request.getSession().removeAttribute("deptName");
		request.getSession().removeAttribute("itemName");
		return "permatters/order_view";
	}
	
	/**
	 * 查询我的预约列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getMyAppointmentList")
	public String getMyAppointmentList(HttpServletRequest request,
			HttpServletResponse response) {
		User user = (User) request.getSession().getAttribute("USER");
		String authToken = user.getAuthToken(); 
		String itemname = request.getParameter("");
		String orderNo = request.getParameter("");
		String currentpage = request.getParameter("currentpage");
		String pagesize = request.getParameter("pagesize");
		String data = null;
		try {
			data  = myAppointmentService.getMyAppointmentList(authToken,orderNo,itemname, currentpage, pagesize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject obj = JSON.parseObject(data);
		List<MyAppointment> list = null;
		if(obj.getString("code").equals("0")){
			String jsonArray = obj.getString("DATA");
			JSONObject date = JSON.parseObject(jsonArray);
			list = JSONArray.parseArray(date.getString("DATA"),MyAppointment.class);
			int currentRows =(int) Math.ceil(Double.parseDouble(date.getString("ROWS"))/Double.parseDouble(pagesize));
			MyAppointment myAppointment = new MyAppointment();
			myAppointment.setCurrentpage(Integer.parseInt(currentpage));
			myAppointment.setPagesize(Integer.parseInt(pagesize));
			myAppointment.setCurrentRows(currentRows);
			request.setAttribute("MyAppointment", myAppointment);
		}else{
			request.setAttribute("tips", "查询失败，请联系管理员！");
			return "user/error";
		}
		request.setAttribute("appointmentList", list);
		return "permatters/orderList";
	}

	/**
	 * 查看预约详情
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getMyAppointmentById")
	public String getMyAppointmentById(HttpServletRequest request,
			HttpServletResponse response) {
		// 根据Id获取详情
		String order_no = request.getParameter("order_no");
		if(StringUtils.isEmpty(order_no)){
			JSONObject json = JSONObject.parseObject(request.getParameter("data"));
			order_no = json.getString("data");
		}
		String data = myAppointmentService.getMyAppointmentById(order_no);
		JSONObject obj = JSON.parseObject(data);
		MyAppointment m = null;
		if("0".equals(obj.getString("code"))){
			m = JSONObject.parseObject(obj.getString("DATA"), MyAppointment.class);
		}else{
			request.setAttribute("tips", "查询失败，请联系管理员！");
			return "user/error";
		}
		request.setAttribute("appointment", m);
		return "permatters/orderDetail";
	}
}
